<template>
  <div class="chart-wrapper" ref="radarChart"></div>
</template>

<script>
/* eslint-disable */
import * as echarts from "echarts";
import {
  onBeforeUnmount,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch,
} from "vue";
import { debounce } from "@/utils/debounce";
import { getindex, getstockindex } from "@/api/stock";
export default {
  name: "stockindexChart",
  props: {
    acode: "",
  },
  setup(props) {
    const radarChart = ref(null);
    let myChart = null;

    const resizeHandler = debounce(() => {
      if (myChart) {
        myChart.resize();
      }
    }, 200);
    onMounted(() => {
      initEcharts();
      window.addEventListener("resize", resizeHandler);
    });
    onBeforeUnmount(() => {
      window.addEventListener("resize", resizeHandler);
    });
    let titledata = "深证大盘指数";
    watch(
      () => props.acode,
      () => {
         titledata=props.acode
        console.log(props.acode, "props>>>>>>>>");
        initEcharts();
      }
    );

    //渲染echarts图
    const initEcharts = () => {
      const colorList = ["#FF9E8C", "#00D2C9"];
      myChart = echarts.init(radarChart.value);

      //   var option;

      var upColor = "#00da3c";
      var downColor = "#ec0000";

      function splitData(rawData) {
        let categoryData = [];
        let values = [];
        let volumes = [];

        for (let i = 0; i < rawData.length; i++) {
          categoryData.push(rawData[i].splice(0, 1)[0]);
          values.push(rawData[i]);

          volumes.push([
            i,
            rawData[i][4],
            rawData[i][0] > rawData[i][1] ? 1 : -1,
          ]);
        }

        return {
          categoryData: categoryData,
          values: values,
          volumes: volumes,
        };
      }

      function calculateMA(dayCount, data) {
        var result = [];
        for (var i = 0, len = data.values.length; i < len; i++) {
          if (i < dayCount) {
            result.push("-");
            continue;
          }
          var sum = 0;
          for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
          }
          result.push(+(sum / dayCount).toFixed(3));
        }
        return result;
      }

      getstockindex(props.acode).then((rawData) => {
        console.log(props.acode, "props.acode+++++");
        let myrawdata = [];
        rawData.data.forEach((element) => {
          let tempdata = [];
          tempdata[0] = element.day;
          tempdata[1] = parseFloat(element.open);
          tempdata[2] = parseFloat(element.close);
          tempdata[3] = parseFloat(element.low);
          tempdata[4] = parseFloat(element.high);
          tempdata[5] = parseFloat(element.volume);
          myrawdata.push(tempdata);
        });

        var data = splitData(myrawdata);

        console.log(data, "show me data+++++");
        let option = {
          // backgroundColor: "#19232d",
          animation: false,
          legend: {
            bottom: 10,
            left: "center",
            data: ["深证指数", "MA5", "MA10", "MA20", "MA30"],
          },
          title: {
            text: titledata,
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
            borderWidth: 1,
            borderColor: "#ccc",
            padding: 10,
            textStyle: {
              color: "#000",
            },
            position: function (pos, params, el, elRect, size) {
              var obj = { top: 10 };
              obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]] = 30;
              return obj;
            },
            // extraCssText: 'width: 170px'
          },
          axisPointer: {
            link: { xAxisIndex: "all" },
            label: {
              backgroundColor: "#777",
            },
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: false,
              },
              brush: {
                type: ["lineX", "clear"],
              },
            },
          },
          brush: {
            xAxisIndex: "all",
            brushLink: "all",
            outOfBrush: {
              colorAlpha: 0.1,
            },
          },
          visualMap: {
            show: false,
            seriesIndex: 5,
            dimension: 2,
            pieces: [
              {
                value: 1,
                color: downColor,
              },
              {
                value: -1,
                color: upColor,
              },
            ],
          },
          grid: [
            {
              left: "10%",
              right: "8%",
              height: "50%",
            },
            {
              left: "10%",
              right: "8%",
              top: "63%",
              height: "16%",
            },
          ],
          xAxis: [
            {
              type: "category",
              data: data.categoryData,
              scale: true,
              boundaryGap: false,
              axisLine: { onZero: false },
              splitLine: { show: false },
              splitNumber: 20,
              min: "dataMin",
              max: "dataMax",
              axisPointer: {
                z: 100,
              },
            },
            {
              type: "category",
              gridIndex: 1,
              data: data.categoryData,
              scale: true,
              boundaryGap: false,
              axisLine: { onZero: false },
              axisTick: { show: false },
              splitLine: { show: false },
              axisLabel: { show: false },
              splitNumber: 20,
              min: "dataMin",
              max: "dataMax",
            },
          ],
          yAxis: [
            {
              scale: true,
              splitArea: {
                show: true,
              },
            },
            {
              scale: true,
              gridIndex: 1,
              splitNumber: 2,
              axisLabel: { show: false },
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: { show: false },
            },
          ],
          dataZoom: [
            {
              type: "inside",
              xAxisIndex: [0, 1],
              start: 98,
              end: 100,
            },
            {
              show: true,
              xAxisIndex: [0, 1],
              type: "slider",
              top: "85%",
              start: 98,
              end: 100,
            },
          ],
          series: [
            {
              name: "深证指数",
              type: "candlestick",
              data: data.values,
              itemStyle: {
                color: upColor,
                color0: downColor,
                borderColor: null,
                borderColor0: null,
              },
              tooltip: {
                formatter: function (param) {
                  param = param[0];
                  return [
                    "Date: " + param.name + '<hr size=1 style="margin: 3px 0">',
                    "Open: " + param.data[0] + "<br/>",
                    "Close: " + param.data[1] + "<br/>",
                    "Lowest: " + param.data[2] + "<br/>",
                    "Highest: " + param.data[3] + "<br/>",
                  ].join("");
                },
              },
            },
            {
              name: "MA5",
              type: "line",
              data: calculateMA(5, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA10",
              type: "line",
              data: calculateMA(10, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA20",
              type: "line",
              data: calculateMA(20, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA30",
              type: "line",
              data: calculateMA(30, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "Volume",
              type: "bar",
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: data.volumes,
            },
          ],
        };
        myChart.setOption(option);

        myChart.dispatchAction({
          type: "brush",
          areas: [
            {
              brushType: "lineX",
              coordRange: [
                data.categoryData[data.categoryData.length - 3],
                data.categoryData[data.categoryData.length - 1],
              ],
              xAxisIndex: 0,
            },
          ],
        });
      });

      // myChart.setOption(option);
    };

    return {
      radarChart,
    };
  },
};
</script>

<style>
</style>